package com.health.ts.service.patientview;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.health.ts.dao.patientview.StDocumentMapper;
import com.health.ts.entity.patientview.StDocument;

/**
 * <p>
 * 患者文书 服务实现类
 * </p>
 *
 * @author ts
 * @since 2017-09-15
 */
@Service
public class StDocumentService extends ServiceImpl<StDocumentMapper, StDocument>  {
	Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Value("${ts.upload.dir}")
	private String uploadBaseDir;// 文件缓存路径
	
	private String patientViewDir="patientview";
	
	/**
	 * 根据患者ID和文书类型获取文书列表
	 * @param patientId
	 * @param documentType
	 * @return
	 */
	public List<StDocument> getDocuments(String patientId,String documentType){
		QueryWrapper<StDocument> wrapper = new QueryWrapper<StDocument>();
		wrapper.eq("patient_id", patientId);
		wrapper.eq("document_type", documentType);
		wrapper.orderByAsc("submit_time");
		return this.list(wrapper);
	}
	
	/**
	 * 根据文书ID获取文书文字内容
	 * @param documentId
	 * @param encode
	 * @return
	 */
	public String getDocumentText(String documentId,String encode){
		String docText = null;
		StDocument document = this.getById(documentId);
		//获取患者编码
		String patientId = document.getPatientId();
		//获取文件名
		String docName = document.getDocumentName()+"."+document.getDocumentFormat();
		String filePath = uploadBaseDir+File.separator+patientViewDir+File.separator+patientId+File.separator+documentId+File.separator+docName;
		File cacheFile = new File(filePath);
		if(cacheFile.exists()){
			//读取本地文件内容返回
			try {
				docText = IOUtils.toString(cacheFile.toURI(),encode);
			} catch (IOException e) {
				log.error("读取本地文件过程中发生异常：",e);
				docText=StringUtils.EMPTY;
			}
		}else{
			//获取Ftp地址
			String docFtpUrl = document.getDocumentUri();
			InputStream in=null;
			try {
				URL url = new URL(docFtpUrl);
				in= url.openConnection().getInputStream();
				docText = IOUtils.toString(in,encode);
				//保存在本地文件缓存
				writeLocalFile(filePath,docText.getBytes());
			} catch (Exception e) {
				log.error("从ftp服务器中获取文件过程中发生异常：",e);
				docText=StringUtils.EMPTY;
			}finally{
				IOUtils.closeQuietly(in, e->{
					log.error("从ftp服务器中获取文件过程中发生异常：",e);
				});
			}
		}
		return docText;
	}
	
	/**
	 * 根据文书ID获取文书字节数组
	 * @param documentId
	 * @param encode
	 * @return
	 */
	public Map<String,Object> getDocumentBytes(String documentId){
		Map<String,Object> result=new HashMap<String,Object>();
		byte[] docBytes = new byte[0];
		StDocument document = this.getById(documentId);
		//获取患者编码
		String patientId = document.getPatientId();
		//获取文件名
		String docName = document.getDocumentName()+"."+document.getDocumentFormat();
		String filePath = uploadBaseDir+File.separator+patientViewDir+File.separator+patientId+File.separator+documentId+File.separator+docName;
		File cacheFile = new File(filePath);
		if(cacheFile.exists()){
			//读取本地文件内容返回
			try {
				docBytes = IOUtils.toByteArray(cacheFile.toURI());
			} catch (IOException e) {
				log.error("读取本地文件过程中发生异常：",e);
			}
		}else{
			//获取Ftp地址
			String docFtpUrl = document.getDocumentUri();
			InputStream in=null;
			try {
				URL url = new URL(docFtpUrl);
				in= url.openConnection().getInputStream();
				docBytes = IOUtils.toByteArray(in);
				//保存在本地文件缓存
				writeLocalFile(filePath,docBytes);
			} catch (Exception e) {
				log.error("从ftp服务器中获取文件过程中发生异常：",e);
			}finally{
				IOUtils.closeQuietly(in, e->{
					log.error("从ftp服务器中获取文件过程中发生异常：",e);
				});
			}
		}
		result.put("fileName", docName);
		result.put("bytes", docBytes);
		return result;
	}
	
	/**
	 * 写入本地文件
	 * @param filePathAndName
	 * @param fileBytes
	 */
	private void writeLocalFile(String filePathAndName,byte[] fileBytes){
		File f = new File(filePathAndName);
		FileOutputStream fos = null;
		try {
			if(!f.exists()){
				File dirs = f.getParentFile();//不存在则新建
				dirs.mkdirs();
				f.createNewFile();
			}
			fos = new FileOutputStream(f);
			IOUtils.write(fileBytes, fos);
		} catch (IOException e) {
			log.error("写入本地文件过程中发生异常：",e);
		}finally{
			IOUtils.closeQuietly(fos, e->{
				log.error("写入本地文件过程中发生异常：",e);
			});
		}
	}
}
